package com.ass.freedom.conf;

import com.ass.freedom.net.boot.BootstrapServer;
import com.ass.freedom.net.boot.NettyBootstrapServer;
import com.ass.freedom.net.boot.Protocols;
import com.ass.freedom.net.boot.ServerProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ObjectUtils;

/**
 * @author syq
 * @date 2019/12/23
 */
@Configuration
@EnableConfigurationProperties({ServerProperty.class})
public class TcpServerAutoConfigure {

    private static final int BLACKLOG = 1024;

    private static final int CPU = Runtime.getRuntime().availableProcessors();

    private static final int SEDU_DAY = 10;

    private static final int TIMEOUT = 120;

    private static final int BUF_SIZE = 10 * 1024 * 1024;


    @Bean(initMethod = "start", destroyMethod = "shutdown")
    @ConditionalOnMissingBean
    public BootstrapServer initServer(ServerProperty serverProperty) {
        if (ObjectUtils.isEmpty(serverProperty.getPort())) {
            throw new NullPointerException("port not defined!");
        }
        if (serverProperty.getBacklog() < 1) {
            serverProperty.setBacklog(BLACKLOG);
        }
        if (serverProperty.getBossThread() < 1) {
            serverProperty.setBossThread(CPU);
        }
        if (serverProperty.getInitalDelay() < 0) {
            serverProperty.setInitalDelay(SEDU_DAY);
        }
        if (serverProperty.getPeriod() < 1) {
            serverProperty.setPeriod(SEDU_DAY);
        }
        if (serverProperty.getHeart() < 1) {
            serverProperty.setHeart(TIMEOUT);
        }
        if (serverProperty.getRevbuf() < 1) {
            serverProperty.setRevbuf(BUF_SIZE);
        }
        if (serverProperty.getWorkThread() < 1) {
            serverProperty.setWorkThread(CPU * 2);
        }
        if (serverProperty.getProtocols() == null) {
            serverProperty.setProtocols(Protocols.USER);
        }
        return new NettyBootstrapServer(serverProperty);
    }


}
